(use-package :leam)
(clc:clc-require :flexi-streams)
(declaim (optimize (speed 0)(safety 3)(debug 3)))

(defclass basic-test-leam-handler()
  ((has-ack
   :initform nil
   :accessor has-ack)
  (has-fin
   :initform nil
   :accessor has-fin)))

(defmethod on-handle-data( (hd basic-test-leam-handler) msg dstream )
  "basic test data handler"
  (let ((test-vec (make-array 3 :element-type '(unsigned-byte 8)
			      :initial-element 3)))
    (assert (= 6 (get-remaining dstream)))
    (assert (= 0 (read-unsigned-8 dstream)))
    (assert (= 255 (read-unsigned-8 dstream)))
    (assert (= 128 (read-unsigned-8 dstream)))
    (read-byte-data dstream test-vec)
    (assert (= 30 (aref test-vec 0)))
    (assert (= 30 (aref test-vec 1)))
    (assert (= 30 (aref test-vec 2)))))

(defmethod on-handle-ack ((hd basic-test-leam-handler) msg )
  (setf (has-ack hd) t))

(defmethod on-handle-fin ((hd basic-test-leam-handler) msg )
  (setf (has-fin hd) t))

(defun basic-leam-stream-test()
  (let* ((left-right (make-instance 'leam-in-memory-io-stream))
	 (right-left (make-instance 'leam-in-memory-io-stream))
	 (handler (make-instance 'basic-test-leam-handler))
	 (left-stream (make-leam-stream right-left left-right handler
					:check-version nil))
	 (right-stream (make-leam-stream left-right right-left handler
					 :check-version nil)))
    (multiple-value-bind
	  ( msg-id outs )
	(begin-send-message left-stream 6)
      (assert (= 1 msg-id))
      (write-unsigned-8 outs 0)
      (write-unsigned-8 outs 255)
      (write-unsigned-8 outs 128)
      (write-byte-data outs (make-array 3 :initial-element 30))
      (assert (= 0 (get-remaining outs)))
      (read-next right-stream)
      (read-next left-stream) ;the ack from the right
      (read-next left-stream) ;the processed from the right
      (assert (eql t (slot-value handler 'has-ack)))
      (assert (eql t (slot-value handler 'has-fin))))))
	   
			     